package com.dhcc.sdc.busi.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.entity.CdcEpisodeEntity;
import com.dhcc.cdc.busi.service.ICdcEpisodeService;
import com.dhcc.cdc.busi.service.ICdcHospitalService;
import com.dhcc.core.config.properties.SysProperties;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.base.warpper.EmptyWarpper;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.result.page.PageFactory;
import com.dhcc.core.framework.security.ShiroKit;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.system.entity.User;
import com.dhcc.sdc.base.service.ISdcBaseAssessmentService;
import com.dhcc.sdc.busi.dto.SdcCaseDto;
import com.dhcc.sdc.busi.dto.SdcEvaluationDto;
import com.dhcc.sdc.busi.entity.SdcBusiQcMrlislogEntity;
import com.dhcc.sdc.busi.entity.SdcBusiQcMrlistEntity;
import com.dhcc.sdc.busi.entity.SdcBusiQcTriggeredEntity;
import com.dhcc.sdc.busi.service.ISdcBusiQcMrlistService;
import com.dhcc.sdc.busi.service.ISdcBusiQcTriggeredService;
import com.dhcc.sdc.busi.service.ISdcCaseService;
import com.dhcc.sds.base.entity.SdsQcentityRuleEntity;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsQcentityRuleService;
import com.dhcc.sds.base.service.ISdsQcentityService;
import com.dhcc.sds.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Controller
@RequestMapping("${sys.backendPath}/sdc/case")
public class SdcCaseController extends BaseController {
    private String PREFIX = "/backend/sdc/case/";

    @Autowired
    private SysProperties sysPro;
    @Autowired
    private ISdcCaseService sdcCaseService;
    @Autowired
    private ICdcHospitalService cdcHospitalService;
    @Autowired
    private ISdsCommonService sdsCommonService;
    @Autowired
    private ISdsQcentityService sdsQcentityService;
    @Autowired
    private ICdcEpisodeService cdcEpisodeService;
    @Autowired
    private ISdsQcentityRuleService sdsQcentityRuleService;
    @Autowired
    private ISdcBusiQcMrlistService sdcBusiQcMrlistService;
    @Autowired
    private ISdcBusiQcTriggeredService sdcBusiQcTriggeredService;
    @Autowired
    private ISdcBaseAssessmentService sdcBaseAssessmentService;
    @RequestMapping("")
    public String caseListPage(Model model) {
        //获取部门信息
        JSONArray officMap = cdcHospitalService.getOfficeMap();
        //加载用户关联科室
        JSONArray departMap = sdsCommonService.getDepartMap(new HashMap<>());
        //获取病种
        JSONArray entityMap = sdsQcentityService.getUpEntityMap();

        model.addAttribute("officeMap", officMap);
        model.addAttribute("departMap", departMap);
        model.addAttribute("entityMap", entityMap);
        model.addAttribute("hospitalId", sdsCommonService.getHospIdBySysUser());
        return PREFIX + "patientlist.html";
    }

    @RequestMapping("/list")
    @ResponseBody
    public Object caseList(@RequestParam Map<String, Object> params) {
        System.out.println(params);
        // 查询登录用户关联科室
        List<String> deptIds = sdsCommonService.getDeptIdsBySysUser();
        params.put("userLinkDepts", deptIds);
        Page<SdcCaseDto> page = new PageFactory<SdcCaseDto>().defaultPage();
        List<SdcCaseDto> result = this.sdcCaseService.page(page, params);
        page.setRecords((List<SdcCaseDto>) new EmptyWarpper(result).warp());
        return R.packForBT(page);
    }

    /**
     * 跳转病种排除页面
     */
    @RequestMapping("/outputMr")
    public String excludeReason(@RequestParam Map<String, Object> params, Model model) {
        Long mrListId = Long.valueOf(params.get("mrListId").toString());
        Long entityId = Long.valueOf(params.get("entityId").toString());
        String execUser = "";
        if (CommonUtil.isNotEmpty(params.get("execUser"))) {
            execUser = java.net.URLDecoder.decode(params.get("execUser").toString());
        } else {
            User user = ShiroKit.getUser();
            execUser = user.getLoginName();
        }
        // 查询入组详细
        Map param = new HashMap();
        param.put("entityId", entityId);
        param.put("isActive", 1);
        param.put("ruleType", 2);
        List<SdsQcentityRuleEntity> ruleDicts = sdsQcentityRuleService.list(param);
        model.addAttribute("mrListId", mrListId);
        model.addAttribute("entityId", entityId);
        model.addAttribute("execUser", execUser);
        model.addAttribute("ruleDicts", ruleDicts);
        return  "/backend/sdc/sdcbaseformshow/sdcexcludereason.html";
    }

    /**
     * 更新表单填报状态
     */
    @RequestMapping(value = "/changeMrStatus")
    @ResponseBody
    public Object changeMrStatus(@RequestParam Map<String, Object> params) {
        String execUser = "手动出组";
        SdcBusiQcMrlistEntity mrListEntity = new SdcBusiQcMrlistEntity();
        if (CommonUtil.isNotEmpty(params.get("execUser"))) {
            execUser = params.get("execUser").toString();
        } else {
            // 获取当前登录用户的部门
            if (ShiroKit.getUser()!=null) {
                User user = ShiroKit.getUser();
                execUser = user.getLoginName();
            }
        }
        if (ShiroKit.getUser()!=null) {
            User user = ShiroKit.getUser();
            mrListEntity.setOutDocId(String.valueOf(user.getId()));
        }
        Date execDate = new Date();
        // 更新填报状态
        Long mrListId  = Long.valueOf(params.get("mrListId").toString());
        String stateCode  = params.get("status").toString();
        String operStartTime = "";
        if (params.get("operStartTime")!=null){
            operStartTime = params.get("operStartTime").toString();
        }
        mrListEntity.setOutDate(execDate);
        mrListEntity.setOutTime(execDate);
        // 查询单病种状态字典，更新当前状态字段
        mrListEntity.setGroupStatus("ActivePart");
        mrListEntity.setState(stateCode);
        mrListEntity.setId(mrListId);
        sdcCaseService.updateById(mrListEntity);
        // 增加病例操作日志
        SdcBusiQcMrlislogEntity mrlislogEntity = new SdcBusiQcMrlislogEntity();
        mrlislogEntity.setMrlistId(mrListId);
        mrlislogEntity.setOperState(stateCode);
        if (params.get("reason")!=null) {
            mrlislogEntity.setOperReason(String.valueOf(params.get("reason")));
        }
        if (params.get("resume")!=null) {
            mrlislogEntity.setOperResume(String.valueOf(params.get("resume")));
        }
        mrlislogEntity.setOperUser(execUser);
        mrlislogEntity.setOperDate(execDate);
        if (CommonUtil.isNotEmpty(operStartTime)){
            Date date = DateUtil.parseTime(operStartTime);
            mrlislogEntity.setOperStartDate(date);
        }
        mrlislogEntity.insert();
        //出组时删除过程质控触发项
        Wrapper<SdcBusiQcTriggeredEntity> triWrapper = new EntityWrapper<SdcBusiQcTriggeredEntity>() ;
        triWrapper.eq("episode_id",mrListEntity.getEpisodeId());
        sdcBusiQcTriggeredService.delete(triWrapper);
        return R.ok();
    }

    /**
     * 跳转到主动入组
     */
    @RequestMapping("/in_group/{episodeId}")
    public String inGroup(@PathVariable Long episodeId, Model model) {
        JSONObject qcentity = sdsQcentityService.getQcentity();
        model.addAttribute("qcentity",qcentity);
        model.addAttribute("cdcEpisodeId",episodeId);

        return "/backend/sdc/sdcbaseformshow/sdcmedicalgroup_in.html";
    }

    /**
     * 修改数据源定义
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(SdcBusiQcMrlistEntity sdcBusiQcMrlistEntity) {
        if (CommonUtil.isOneEmpty(sdcBusiQcMrlistEntity)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        String execUser = "手动入组";
        if (ShiroKit.getUser()!=null) {
            User user = ShiroKit.getUser();
            execUser = user.getLoginName();
            sdcBusiQcMrlistEntity.setInUserId(String.valueOf(user.getId()));
            sdcBusiQcMrlistEntity.setInLocId(String.valueOf(user.getDeptId()));
        }
        CdcEpisodeEntity episodeEntity = cdcEpisodeService.selectById(sdcBusiQcMrlistEntity.getEpisodeId());
        sdcBusiQcMrlistEntity.setInWardId(episodeEntity.getAdmWardId().toString());
        sdcBusiQcMrlistEntity.setInDate(new Date());
        sdcBusiQcMrlistEntity.setInTime(new Date());
        sdcBusiQcMrlistEntity.setState("I");
        sdcBusiQcMrlistEntity.setGroupStatus("ActivePart");
        Map<String,Object> params = new HashMap<>();
        params.put("episodeId", sdcBusiQcMrlistEntity.getEpisodeId());
        List<SdcBusiQcMrlistEntity> list = sdcBusiQcMrlistService.list(params);
        if (list.size() != 0){
            for (SdcBusiQcMrlistEntity mrlistEntity : list) {
                mrlistEntity.setGroupStatus("Stop");
            }
            sdcCaseService.updateBatchById(list);
        }
        boolean insert = sdcBusiQcMrlistEntity.insert();
        String reason = sdcBusiQcMrlistEntity.getReason();
        if (insert){
            SdcBusiQcMrlislogEntity mrlislogEntity = new SdcBusiQcMrlislogEntity();
            mrlislogEntity.setMrlistId(sdcBusiQcMrlistEntity.getId());
            mrlislogEntity.setOperState("I");
            //TODO 获取当前用户
            /*sdsQcincaseOperlogEntity.setOperUser(cdcEpisodeEntity.getAdmDoctorName());*/
            mrlislogEntity.setOperDate(new Date());
            mrlislogEntity.setOperReason(reason);
            mrlislogEntity.setOperUser(execUser);
            mrlislogEntity.insert();
        }
        return R.ok();
    }

    /**
     * @Desc 生成excel文件
     * @param params
     * @return
     * @Author syj
     * @Date 2022年05月31日07:53:00
     */
    @RequestMapping(value = "/createExcel")
    @ResponseBody
    public Object createExcel(@RequestParam Map<String, Object> params) {
        // 查询登录用户关联科室
        List<String> deptIds = sdsCommonService.getDeptIdsBySysUser();
        params.put("userLinkDepts", deptIds);
        String fileName = this.sdcCaseService.createExcel(params);
        return R.ok(fileName);
    }

    /**
     * @Desc 下载生成的Excel文件  .+ 后面的解决小数点取值不全问题
     * @param fileName
     * @param resp
     * @throws IOException
     * @Author syj
     * @Date 2022年6月14日 上午11:26:34
     */
    @RequestMapping(value = "excelDown/{fileName:.+}")
    @ResponseBody
    public void excelDown(@PathVariable String fileName, HttpServletResponse resp) throws IOException{
        String filePath = sysPro.getSysHome()+"file_download/sdc/case/";
        String excelFile = filePath + fileName;
        File file = new File(excelFile);
        if(file.exists()){
            //将文件名设置为中文
            byte[] tmpb = fileName.getBytes("GBK");
            String fileNameCN = new String(tmpb, "8859_1");
            resp.setContentType("application/octet-stream");
            resp.setHeader("Content-Disposition","attachment;filename=" + fileNameCN);
            resp.setContentLength((int) file.length());
            //打开指定文件流
            BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(excelFile));
            //写出流信息
            byte[] bytes =new byte[1024];
            OutputStream os = resp.getOutputStream();
            BufferedOutputStream fosObject = new BufferedOutputStream(os);
            while (fileInputStream.read(bytes)!=-1) {
                fosObject.write(bytes);
            }
            fileInputStream.close();
            fosObject.close();
            os.flush();
            os.close();
        }
    }
    //评估列表
    @RequestMapping("/evaluationListPage")
    public String evaluationListPage(Model model) {
        //获取部门信息
        JSONArray officMap = cdcHospitalService.getOfficeMap();
        //加载用户关联科室
        JSONArray departMap = sdsCommonService.getDepartMap(new HashMap<>());
        //获取病种
        JSONArray entityMap = sdsQcentityService.getUpEntityMap();
        //获取评估表名称
        JSONArray assessmentMap = sdcBaseAssessmentService.getJSONArray();
        model.addAttribute("officeMap", officMap);
        model.addAttribute("departMap", departMap);
        model.addAttribute("entityMap", entityMap);
        model.addAttribute("assessmentMap", assessmentMap);
        return PREFIX + "evaluationlist.html";
    }

    @RequestMapping("/evaluationList")
    @ResponseBody
    public Object evaluationList(@RequestParam Map<String, Object> params) {
        // 查询登录用户关联科室
        List<String> deptIds = sdsCommonService.getDeptIdsBySysUser();
        params.put("userLinkDepts", deptIds);
        Page<SdcEvaluationDto> page = new PageFactory<SdcEvaluationDto>().defaultPage();
        List<SdcEvaluationDto> result = this.sdcCaseService.evaluationPage(page, params);
        page.setRecords((List<SdcEvaluationDto>) new EmptyWarpper(result).warp());
        return R.packForBT(page);
    }

    //评估列表明细
    @RequestMapping("/toEvaluationDetail")
    public String toEvaluationDetail(@RequestParam Map<String, Object> map,Model model) {
        model.addAttribute("evalId", map.get("key"));
        model.addAttribute("patientId", map.get("patientId"));
        model.addAttribute("asmId", map.get("asmId"));
        model.addAttribute("entityId", map.get("entityId"));
        return PREFIX + "evaluationDetail.html";
    }
}
